//
//  NearbyViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-4.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "NearbyViewController.h"
#import "ShopHomeViewController.h"
#import "SelectCuisinesView.h"
#import "ShopInfoCell.h"

#define DISTANCE @"1000"

@interface NearbyViewController ()

@property (nonatomic, strong) SelectCuisinesView *selectCuisinesView;
@property (nonatomic, strong) SelectDistanceView *selectDistanceView;

@property (nonatomic, strong) NSString *cuisinesId;
@property (nonatomic, strong) NSString *distance;

@end

@implementation NearbyViewController

#pragma 初始化
- (id)init
{
    self = [super initWithNibClass:[NearbyViewController class]];
    if (self) {
        //默认菜系、商圈、排序都为空
        _cuisinesId = _distance = S_EMPTY;
        _dataSource = [[NearbyDataSource alloc] initWithVC:self];
    }
    return self;
}

#pragma 视图加载完成
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [[BaseDataManager sharedInstance] startDownLoad];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //查询附近1000米
    [_dataSource fetchShopWithCuisines:S_EMPTY distance:S_EMPTY isLoadMore:NO];
}

#pragma 初始化UI
- (void)setupUI
{
    [self createNavigation:@"附近餐厅"];
//    [self createRightButtonWithTitle:S_EMPTY background:NAV_SEARCH_BACKGROUND frame:CGRectMake(0, 0, 30, 30)];
    
    //创建菜单选项
    [self setupToolsView];
    
    //设置Tableview的数据源
    self.shopTable.delegate = _dataSource;
    self.shopTable.dataSource = _dataSource;
}

#pragma 添加选择距离和餐厅类型的菜单
- (void)setupToolsView
{
    //选择餐厅类型菜单
    _selectCuisinesView = [[SelectCuisinesView alloc]
                           initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectCuisinesView.delegate = self;
    [self.view addSubview:_selectCuisinesView];
    
    //选择距离菜单
    _selectDistanceView = [[SelectDistanceView alloc]
                           initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectDistanceView.delegate = self;
    [self.view addSubview:_selectDistanceView];
}

#pragma 返回按钮事件
- (void)leftButtonClick:(id)sender
{
    [AppDelegate changeToNormalTabBar];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma 弹出选择菜系菜单
- (IBAction)selectCuisinesAction:(id)sender
{
    [_selectCuisinesView showOrVisible];
    [_selectDistanceView hidden];
}

#pragma 选择菜系选项
- (void)selectCuisinesFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"lx_name"];
    _cuisinesId = [selectedData objectForKey:@"id"];
    
    [self.dishCatToolButton setTitleForNormal:title];
    
    [_dataSource fetchShopWithCuisines:_cuisinesId distance:_distance isLoadMore:NO];
}

#pragma 弹出选择商圈菜单
- (IBAction)selectedAreaAction:(id)sender
{
    [_selectDistanceView showOrVisible];
    [_selectCuisinesView hidden];
}

#pragma 选择商圈信息
- (void)selectDistanceFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"display"];
    _distance = [selectedData objectForKey:@"juli"];
    
    _distanceToolButton.selected = ![_distance isEqualToString:@""];
    
    [self.distanceToolButton setTitleForNormal:title];
    
    [_dataSource fetchShopWithCuisines:_cuisinesId distance:_distance isLoadMore:NO];
}

#pragma 将分页加载的数据添加到tableview后面
- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.shopList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.shopList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [self.shopTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    
    self.moreLoading = NO;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation NearbyDataSource

#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _shopList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

#pragma 获取附近餐厅信息
- (void)fetchShopWithCuisines:(NSString*)cuisinesId distance:(NSString*)distance isLoadMore:(BOOL)isLoadMore
{
    if (!isLoadMore) [SVProgressHUD show];
    
    //根据是否加载更多判断是加载第一页还是第几页
    self.pageNumber = isLoadMore ? self.pageNumber : 1;
    
    NSString *url = [NSString stringWithFormat:API_SHOP_LIST_NEARBY,[AppSetting longitude],[AppSetting latitude],cuisinesId,distance,self.pageNumber, [AppSetting cityId]];
    
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *json = [request.responseData JSONValue];
    //从新获取餐厅信息，是取第一页
    if (request.tag == FETCH_NEW_TAG) {
        
        self.shopList = [json objectForKey:@"data"];
        
        [self.viewController.shopTable reloadData];
        [self.viewController.shopTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    }
    //分页获取餐厅信息，是加载更多
    if (request.tag == FETCH_MORE_TAG) {
        [self.viewController appendTableWith:[json objectForKey:@"data"]];
    }
    
    [SVProgressHUD dismiss];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shopList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ShopInfoCell";
    
    ShopInfoCell *cell = (ShopInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ShopInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
    
    NSString *shopId = [dic objectForKey:@"id"];
    
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    shopHomeVC.parentViewController = self.viewController;
    shopHomeVC.shopId = shopId;
    
    [AppDelegate changeToShopTabBar:shopHomeVC];
    
    [self.viewController.navigationController pushViewController:shopHomeVC animated:YES];
}

-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _shopList.count-2) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            
            [self fetchShopWithCuisines:_viewController.cuisinesId distance:_viewController.distance isLoadMore:YES];
            
            self.viewController.moreLoading = YES;
        }
    }
}

@end